import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  FlatList,
  Dimensions,
  TouchableOpacity,
  Animated,
  Easing,
  ViewStyle,
  Image
} from 'react-native';
// import Echarts from 'react-native-echarts-wrapper';
import { useNavigation } from '@react-navigation/native';
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { useResponsiveContext } from '../components/ResponsiveProvider';
import ResponsiveText from '../components/ResponsiveText';
import ResponsiveView from '../components/ResponsiveView';
import { wp, hp, sp } from '../utils/layout';
import { createResponsiveStyles } from '../utils/StyleUtils';

const { width: screenWidth } = Dimensions.get('window');

type KeyIssue = {
  id: string;
  title: string;
  content: string;
  severity: 'high' | 'medium' | 'low';
};

const HealthReportScreen: React.FC = () => {
  const navigation = useNavigation();
  const [systolicData] = useState([135, 138, 142, 140, 144]);
  const [diastolicData] = useState([85, 88, 90, 89, 92]);
  const dates = ['6/1', '6/5', '6/10', '6/15', '6/20'];
  const [keyIssues, setKeyIssues] = useState<KeyIssue[]>([]);
  const pulseAnim = new Animated.Value(0);

  useEffect(() => {
    Animated.loop(
      Animated.sequence([
        Animated.timing(pulseAnim, {
          toValue: 1,
          duration: 1000,
          easing: Easing.inOut(Easing.ease),
          useNativeDriver: true
        }),
        Animated.timing(pulseAnim, {
          toValue: 0,
          duration: 1000,
          easing: Easing.inOut(Easing.ease),
          useNativeDriver: true
        })
      ])
    ).start();

    setTimeout(() => {
      setKeyIssues([
        {
          id: '1',
          title: '血压波动明显',
          content: '您的收缩压和舒张压都出现了明显的波动，尤其是在近期测量中显示升高趋势。',
          severity: 'high'
        },
        {
          id: '2',
          title: '用药建议',
          content: '建议遵医嘱按时服用降压药物，保持规律的服药时间，避免漏服或随意改变剂量。',
          severity: 'medium'
        },
        {
          id: '3',
          title: '生活方式调整',
          content: '注意控制饮食盐分摄入，保持适度运动，避免情绪波动和熬夜。',
          severity: 'high' // 修改此处
        },
        {
          id: '4',
          title: '专家咨询建议',
          content: '建议咨询在线专家，讨论是否需要调整用药方案。增加血压监测频率，每天固定时间测量。',
          severity: 'medium'
        }
      ]);
    }, 500);
  }, []);

  const pulseStyle = {
    transform: [{
      scale: pulseAnim.interpolate({
        inputRange: [0, 1],
        outputRange: [1, 1.05]
      })
    }]
  };

  const getLineStyle = (index: number, startPos: number, endPos: number): ViewStyle => {
    const segmentWidth = 100 / (systolicData.length - 1);
    const angle = Math.atan2(endPos - startPos, segmentWidth);
    return {
      position: 'absolute',
      left: `${(index / (systolicData.length - 1)) * 100}%`,
      width: `${segmentWidth}%`,
      bottom: startPos,
      transform: [{
        rotate: `${angle}rad`
      }],
      backgroundColor: '#FF5252',
      height: 1,
    };
  };

  const getDataPointStyle = (index: number, value: number): ViewStyle => ({
    position: 'absolute',
    left: `${(index / (systolicData.length - 1)) * 100}%`,
    bottom: ((180 - value) / 180) * 100,
    backgroundColor: '#FF5252',
    width: 8,
    height: 8,
    borderRadius: 4,
    transform: [{ translateX: -4 }, { translateY: 4 }],
  });

  const renderItem = ({ item }: { item: KeyIssue }) => {
    const colors = {
      high: ['rgb(232,245,254)', 'rgb(232,245,254)'],
      medium: ['rgb(231,254,238)', 'rgb(231,254,238)'],
      low: ['rgb(232,245,254)', 'rgb(232,245,254)']
    };

    return (
      <Animated.View style={[styles.issueCardWrapper, pulseStyle]}>
        <LinearGradient
          colors={colors[item.severity]}
          style={styles.issueCard}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
        >
          <View style={styles.issueHeader}>
            {/* 修改标题颜色为黑色 */}
            <Text style={[styles.issueTitle, { color: '#000' }]}>{item.title}</Text>
          </View>
          {/* 修改内容颜色为黑色 */}
          <Text style={[styles.issueContent, { color: '#000' }]}>{item.content}</Text>
          <View style={styles.issueFooter}>
            {item.severity === 'high' ? (
              <Image
                source={require('./assets/gan.png')}
                style={{ width: 50, height: 50 }}
              />
            ) : item.severity === 'medium' ? (
              <Image
                source={require('./assets/yao.png')}
                style={{ width: 50, height: 50 }}
              />
            ) : (
              null // 处理 low 情况
            )}
          </View>
        </LinearGradient>
      </Animated.View>
    );
  };

  return (
    <ResponsiveView style={styles.container}>
      {/* 头部导航栏 */}
      <ResponsiveView style={styles.header}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => navigation.goBack()}
        >
          <Icon name="arrow-back" size={24} color="#333" />
        </TouchableOpacity>
        <ResponsiveText style={styles.headerTitle}>健康预警报告</ResponsiveText>
        <View style={styles.headerRight} />
      </ResponsiveView>

      <ScrollView
        contentContainerStyle={styles.scrollViewContainer}
        showsVerticalScrollIndicator={false}
      >
        {/* 头部区域 */}
        <View style={styles.headerContainer}>
          <Text style={styles.headerGradientTitle}>指标预警</Text>
          <Text style={styles.headerGradientTitlee}>中度风险</Text>
          <Text style={styles.headerGradientTitlel}>您的血压指标近期有波动，建议及时进行复查并调整用药方案。</Text>
        </View>



        {/* 血压趋势图 */}
        <View style={styles.section}>

          <View style={styles.sectionHeader}>
            <Icon name="show-chart" size={20} color="#4A90E2" />
            <Text style={styles.sectionTitle}>血压趋势图</Text>
          </View>
          {/* 浮动健康概览卡片 */}
          <View style={styles.floatingCardsContainer}>
            <View style={[styles.floatingCard, styles.currentPressureCard]}>
              <Text style={[styles.overviewValue]}>
                145/95
              </Text>
              <Text style={styles.overviewLabel}>
                当前血压
              </Text>
              <Text style={styles.overviewUnit}>↑ 较上次升高</Text>
            </View>

            <View style={[styles.floatingCard, styles.averagePressureCard]}>
              <Text style={[styles.overviewValue]}>
                138/88
              </Text>
              <Text style={styles.overviewLabel}>
                平均血压
              </Text>
              <Text style={styles.overviewUnit}>↑ 近期上升</Text>
            </View>
          </View>
          <View style={styles.legend}>
            <View style={styles.legendItem}>
              <View style={[styles.legendColor, { backgroundColor: '#C33E39' }]} />
              <Text style={styles.legendText}>收缩压</Text>
            </View>
            <View style={styles.legendItem}>
              <View style={[styles.legendColor, { backgroundColor: '#4A90E2' }]} />
              <Text style={styles.legendText}>舒张压</Text>
            </View>
          </View>
          <View style={styles.chartContainer}>
            {/* Y轴标签 */}
            <View style={styles.chartYAxis}>
              {[150, 120, 90, 60, 30].map((value) => (
                <Text key={value} style={styles.chartYLabel}>{value}</Text>
              ))}
            </View>

            {/* 图表主体 */}
            <View style={styles.chartMain}>
              {/* 网格线 */}
              {[0, 20, 40, 60, 80, 100].map((percent) => (
                <View
                  key={`grid-${percent}`}
                  style={[styles.gridLine, { top: `${percent}%` }]}
                />
              ))}

              {/* 收缩压数据线 */}
              <View style={styles.dataLine}>
                {systolicData.map((value, index) => {
                  const nextValue = systolicData[index + 1];
                  if (!nextValue) return null;

                  const startPos = ((180 - value) / 180) * 100;
                  const endPos = ((180 - nextValue) / 180) * 100;

                  return (
                    <View
                      key={`line-${index}`}
                      style={[
                        styles.lineSegment,
                        getLineStyle(index, startPos, endPos)
                      ]}
                    />
                  );
                })}
              </View>

              {/* 数据点 */}
              {systolicData.map((value, index) => (
                <View
                  key={`point-${index}`}
                  style={[
                    styles.dataPoint,
                    getDataPointStyle(index, value)
                  ]}
                />
              ))}
            </View>
          </View>

          {/* X轴标签 */}
          <View style={styles.chartXAxis}>
            {dates.map((date, index) => (
              <Text key={index} style={styles.chartXLabel}>{date}</Text>
            ))}
          </View>

          {/* 图例 */}

        </View>

        {/* 健康建议 */}
        <View style={styles.sectionn}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>根据您近期的血压数据分析，我们发现以下几个关键问题:</Text>
          </View>
          <FlatList
            data={keyIssues}
            renderItem={renderItem}
            keyExtractor={item => item.id}
            horizontal
            showsHorizontalScrollIndicator={false}
            snapToInterval={screenWidth * 0.8 - 40}
            decelerationRate="fast"
            contentContainerStyle={styles.issuesList}

          />
        </View>
        {/* 行动建议 */}
      </ScrollView>
    </ResponsiveView>
  );
};

const styles = createResponsiveStyles({
  container: {
    flex: 1,
    backgroundColor: '#F5F7FA',
  },
  header: {
    width: '100%',
    height: 64,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: wp(16),
    paddingVertical: hp(12),
    backgroundColor: '#fff',
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#E0E0E0',
  },
  backButton: {
    padding: wp(4),
  },
  headerTitle: {
    height: hp(24),
    fontSize: sp(18),
    fontWeight: 'bold',
    color: '#333',
    textAlign: 'center',
    flex: 1,
    marginHorizontal: wp(16),
  },
  headerRight: {
    width: wp(24),
  },
  scrollViewContainer: {
    paddingBottom: hp(20),
  },
  headerContainer: {
    backgroundColor: 'white',
    width: wp(321),
    height: hp(114),
    marginTop: hp(10),
    paddingHorizontal: wp(15),
    marginLeft: wp(20),
    borderRadius: 15,
    paddingVertical: hp(15),
  },
  floatingCardsContainer: {
    width: wp(335),
    height: hp(107),
    marginLeft: wp(-18),

    // borderRightColor:'pink',
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: wp(20),
    marginTop: hp(-30),
    zIndex: 1,
  },
  floatingCard: {
    width: '48%',
    backgroundColor: 'rgb(247, 248, 250)',
    borderRadius: 12,
    padding: wp(15),
    // shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.1,
    shadowRadius: 6,
    elevation: 4,
    alignItems: 'center',
    justifyContent: 'center',
  },
  currentPressureCard: {
    borderTopWidth: 6,
    borderTopColor: 'rgb(247, 248, 250)',
  },
  averagePressureCard: {
    borderTopWidth: 6,
    borderTopColor: 'rgb(247, 248, 250)',
  },
  overviewLabel: {
    fontSize: sp(14),
    color: '#666',
    marginBottom: hp(8),
  },
  overviewValue: {
    fontSize: sp(22),
    // fontWeight: '700',
    marginBottom: hp(4),
  },
  overviewUnit: {
    fontSize: sp(12),
    fontWeight: 'normal',
    color: 'red',
  },
  section: {
    height: hp(391),
    backgroundColor: '#FFF',
    borderRadius: 12,
    padding: wp(15),
    marginHorizontal: wp(15),
    marginBottom: hp(15),
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.08,
    shadowRadius: 5,
    elevation: 2,
    marginTop: hp(14)
  },
  sectionn: {
    height: hp(380),
    backgroundColor: '#FFF',
    borderRadius: 12,
    padding: wp(15),
    marginHorizontal: wp(15),
    marginBottom: hp(15),
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.08,
    shadowRadius: 5,
    elevation: 2,
    marginTop: hp(14)
  },
  sectionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: hp(40)
  },
  sectionTitle: {
    fontSize: sp(16),
    // fontWeight: '600',
    color: '#333',
    marginLeft: wp(8),
    // marginBottom: hp(35)
  },
  chartContainer: {
    marginTop: hp(20),
    flexDirection: 'row',
    height: hp(160),
    marginVertical: hp(10)
  },
  chartYAxis: {
    width: wp(25),
    justifyContent: 'space-between',
    marginRight: wp(8)
  },
  chartYLabel: {
    fontSize: sp(10),
    color: '#666'
  },
  chartMain: {
    flex: 1,
    borderLeftWidth: 1,
    borderBottomWidth: 1,
    borderColor: '#DDD',
    position: 'relative'
  },
  gridLine: {
    position: 'absolute',
    left: 0,
    right: 0,
    height: 1,
    backgroundColor: 'rgba(0,0,0,0.05)'
  },
  dataLine: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0
  },
  lineSegment: {
    position: 'absolute',
    transformOrigin: 'left center',
  },
  dataPoint: {
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
  },
  chartXAxis: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginLeft: wp(30),
    marginTop: hp(3)
  },
  chartXLabel: {
    fontSize: sp(10),
    color: '#666',
    width: `${100 / 7}%`,
    textAlign: 'center'
  },
  legend: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: hp(10)
  },
  legendItem: {
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: wp(10)
  },
  legendColor: {
    width: 16,
    height: 3,
    // borderRadius: 5,
    marginRight: 4
  },
  legendText: {
    fontSize: sp(10),
    color: '#666'
  },
  issuesList: {
    paddingVertical: 8
  },
  issueCardWrapper: {
    width: wp(245),
    paddingHorizontal: 8,
    height: hp(245),
    marginRight: 10,
    // backgroundColor: 'blue',

  },
  issueCard: {
    flex: 1,
    borderRadius: 12,
    padding: 15,
    justifyContent: 'space-between',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 3 },
    shadowOpacity: 0.15,
    shadowRadius: 5,
    elevation: 3,

    // borderRightColor:'pink'
  },
  issueHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
    // borderRightColor:'pink'
  },
  issueIcon: {
    marginRight: 8
  },
  issueTitle: {
    fontSize: 24,
    fontWeight: '500',
    color: '#FFF'
  },
  issueContent: {
    fontSize: 16,
    lineHeight: 23,
    color: 'rgba(29,33,41,1)',
    marginBottom: 10,
    textAlign: 'left',
    fontFamily: 'PingFangSC-regular'
  },
  issueFooter: {
    alignSelf: 'flex-end'
  },
  severityText: {
    fontSize: 10,
    color: '#FFF',
    fontWeight: '500',
    // backgroundColor: 'rgba(0,0,0,0.2)',
    paddingHorizontal: 8,
    paddingVertical: 2,
    borderRadius: 8
  },
  actionSection: {
    backgroundColor: '#FFF',
    borderRadius: 12,
    padding: 15,
    marginHorizontal: 15,
    marginBottom: 15
  },
  actionTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    marginBottom: 12
  },
  actionCards: {
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  actionCard: {
    width: '30%',
    aspectRatio: 1,
    borderRadius: 10,
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 3,
    elevation: 2,
    padding: 10
  },
  actionText: {
    fontSize: 12,
    color: '#FFF',
    marginTop: 8,
    fontWeight: '500',
    textAlign: 'center'
  },
  headerGradientTitle: {
    fontSize: sp(16),
    textAlign: "left",
    lineHeight: 23,
    color: '#000',
    marginBottom: hp(3)
  },
  headerGradientTitlel: {
    fontSize: sp(16),
    textAlign: "left",
    lineHeight: 23,
    marginTop: hp(4),
    color: 'gray',
    marginBottom: hp(3),
  },
  headerGradientTitlee: {
    fontSize: sp(14),
    textAlign: "right",
    lineHeight: 23,
    marginTop: hp(-20),
    color: 'red',
    marginBottom: hp(3),
  }
});

export default HealthReportScreen;